package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.HotDataCache;
import com.sky.constant.CacheConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    // 获取热门套餐ID列表
    public List<Long> getHotSetmealIds(int limit) {
        return setmealMapper.getHotSetmealIds(limit);
    }


    /**
     * 根据id查询套餐和套餐菜品关系
     * @param id
     * @return
     */
    @HotDataCache(
            cacheName = CacheConstant.SETMEAL_CACHE,
            lockWaitTime = 5000,
            lockHoldTime = 10000,
            maxRetryCount = 3,
            retryIntervalMs = 500
    )
    public SetmealVO getByIdWithDish(Long id) {
        //通过id查询套餐数据
        Setmeal setmeal = setmealMapper.getByID(id);
        //通过id查询套餐菜品关系数据
        List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);
        //封装套餐VO数据
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);

        return setmealVO;
    }

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDTO
     * @return
     */
    @Transactional
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.SETMEAL_PAGE_CACHE,
                            allEntries = true
                    ),
                    // 第二个缓存操作：删除所有按类型分类查询缓存
                    @CacheEvict(
                            value = CacheConstant.CATEGORY_LIST_CACHE,
                            allEntries = true
                    )
            }
    )
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);

        //向套餐表中插入数据
        setmealMapper.insert(setmeal);
        //获取生成的套餐id
        Long setmealId = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });

        //保存套餐和菜品的关联关系
        setmealMapper.insertBatch(setmealDishes);
        return ;
    }

    /**
     * 套餐分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    @Cacheable(cacheNames = CacheConstant.SETMEAL_PAGE_CACHE,
            key = "'page='+#setmealPageQueryDTO.page+'-pageSize='+#setmealPageQueryDTO.pageSize" +
            "+'-categoryId='+#setmealPageQueryDTO.categoryId+'-status='+#setmealPageQueryDTO.status" +
            "+'-name='+#setmealPageQueryDTO.name", // 包含所有筛选参数
            condition = "#setmealPageQueryDTO != null" // 过滤空参数
    )
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除套餐
     * @param ids
     */
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.SETMEAL_PAGE_CACHE,
                            allEntries = true // 删除该缓存下所有数据
                    ),
                    // 第二个缓存操作：删除所有套餐缓存
                    @CacheEvict(
                            value = CacheConstant.SETMEAL_CACHE,
                            allEntries = true
                    ),
                    // 第三个缓存操作：删除所有按类型分类查询缓存
                    @CacheEvict(
                            value = CacheConstant.CATEGORY_LIST_CACHE,
                            key = "2"
                    )
            }
    )
    public void delete(List<Long> ids) {
        //判断是否存在在售的套餐
        for (Long id : ids){
            Setmeal setmeal = setmealMapper.getByID(id);
            if (setmeal.getStatus() == StatusConstant.ENABLE){
                //存在在售的套餐
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }

        //删除套餐数据
        setmealMapper.deleteBatch(ids);
        //删除套餐和菜品的关联数据
        for (Long id : ids) {
            setmealDishMapper.deleteBySetmealId(id);
        }
    }

    /**
     * 修改套餐以及套餐菜品关系
     * @param setmealDTO
     * @return
     */
    @Transactional
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.SETMEAL_PAGE_CACHE,
                            allEntries = true
                    ),
                    // 第二个缓存操作：删除所有按类型分类查询缓存
                    @CacheEvict(
                            value = CacheConstant.CATEGORY_LIST_CACHE,
                            allEntries = true
                    ),
                    // 第三个缓存操作：删除该套餐缓存
                    @CacheEvict(
                            value = CacheConstant.SETMEAL_CACHE,
                            key = "#setmealDTO.id"
                    )
            }
    )
    public void updateWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        //修改套餐表基础信息
        setmealMapper.update(setmeal);

        //删除套餐关系表
        setmealDishMapper.deleteBySetmealId(setmealDTO.getId());
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        //重新插入套餐关系表
        if (setmealDishes != null && setmealDishes.size() > 0){
            setmealDishes.forEach(setmealDish -> {
                //为每个套餐菜品关系设置套餐id
                setmealDish.setSetmealId(setmealDTO.getId());
            });
            //插入
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    /**
     * 套餐起售停售
     * @param status
     * @param id
     */
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.SETMEAL_PAGE_CACHE,
                            allEntries = true
                    ),
                    // 第二个缓存操作：删除所有按类型分类查询缓存
                    @CacheEvict(
                            value = CacheConstant.CATEGORY_LIST_CACHE,
                            allEntries = true
                    ),
                    // 第三个缓存操作：删除该套餐缓存
                    @CacheEvict(
                            value = CacheConstant.SETMEAL_CACHE,
                            key = "#id"
                    )
            }
    )
    public void startOrStop(Integer status, Long id) {
        //如果是起售套餐，检查套餐内是否有停售菜品
        if (status == StatusConstant.ENABLE){
            //通过套餐id获得套餐内的菜品
            List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);
            if (setmealDishes != null && setmealDishes.size() > 0){
                //检查菜品是否处于停售状态
                for (SetmealDish setmealDish : setmealDishes) {
                    //通过菜品id查询菜品数据
                    Dish dish = dishMapper.getById(setmealDish.getDishId());
                    if (dish.getStatus() == StatusConstant.DISABLE){
                        //当前菜品处于停售状态,不能起售套餐
                        throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                }
            }
        }

        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);
    }

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    @Cacheable(cacheNames = CacheConstant.SETMEAL_DISH_CACHE,
            key = "#id",
            condition = "#id != null")
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
